package com.wang.service.impl;

import com.aaa.entity.OOrder;
import com.aaa.security.util.WebUtils;
import com.aaa.util.JwtUtil;
import com.aaa.vo.Result;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.aaa.entity.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wang.feigen.RabbitmqFeigen;
import com.wang.mapper.*;
import com.wang.service.openfeign.WXFeign;
import com.wang.service.OOrderService;
import com.wang.mapper.OOrderMapper;
import com.wang.service.PayService;
import com.wang.vo.OrderFormVo;
import com.wang.vo.PayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.wang.vo.GoodsVo1;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class OOrderServiceImpl extends ServiceImpl<OOrderMapper, OOrder>
        implements OOrderService {
    @Autowired
    private OOrderMapper orderMapper;

    @Autowired
    private OOrderMapper mapper;
    @Autowired
    private GGoodsMapper goodsMapper;
    @Autowired
    private RabbitmqFeigen rabbitmqFeigen;
    @Autowired
    private UUserInfoMapper uUserInfoMapper;
    @Autowired
    private OPayLogMapper oPayLogMapper;
    @Autowired
    private OStockMapper oStockMapper;
    @Autowired
    private OcartDao ocartDao;
    @Autowired
    private PayService payService;

    @Autowired
    private WXFeign wxFeign;
    @Override
    public Result fandAll(Integer pageCurrent, Integer pageSize, Integer state) {
        String token = WebUtils.getRequest().getHeader("token");
        Map<String, Object> tokenChaim = JwtUtil.getTokenChaim(token);
        String username = (String) tokenChaim.get("username");
        PageHelper.startPage(pageCurrent, pageSize);



        if (state != null) {
            List<OrderFormVo> order = orderMapper.findOrder(state, username);
            PageInfo<OrderFormVo> orderPageInfo = new PageInfo<>(order);
            return new Result<>(2000, "查询成功", orderPageInfo);
        }
        List<OrderFormVo> ordert = orderMapper.findOrdert(username);
        PageInfo<OrderFormVo> orderPageInfo = new PageInfo<>(ordert);
        return new Result<>(2000, "查询成功", orderPageInfo);
    }


    @Override
    public Result deleteOrder(String code) {
        int i = orderMapper.deleteBycoded(code);
        return new Result<>(2000, "删除成功", i);
    }

    @Override
    public Result updateOrder(String id) {
        QueryWrapper<OOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        OOrder oOrder = orderMapper.selectOne(wrapper);
        oOrder.setState(3);
        Integer num = oOrder.getNum();
        int i = orderMapper.updateById(oOrder);
        if (i > 0) {
            return new Result<>(2000, "订单失效", i);
        }
        return new Result<>(5000, "订单异常");
    }

    @Override
    public Result updateOrderqx(String id) {
        QueryWrapper<OOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        OOrder oOrder = orderMapper.selectOne(wrapper);
        oOrder.setState(4);
        int i = orderMapper.updateById(oOrder);
        if (i > 0) {
            return new Result<>(2000, "订单取消", i);
        }
        return new Result<>(5000, "订单异常");
    }

    @Override
    public Result pay(Integer paysort, String code) throws IOException {
        QueryWrapper<OPayLog> oPayLogQueryWrapper = new QueryWrapper<>();
        oPayLogQueryWrapper.eq("order_no",code);
        List<OPayLog> oPayLogs = oPayLogMapper.selectList(oPayLogQueryWrapper);
        OPayLog oPayLog = oPayLogs.get(0);
        PayUtils payUtils = new PayUtils();
        System.out.println("payUtils ==================================== " + oPayLog);
        payUtils.setTotalmoney(oPayLog.getTotalFee());
        payUtils.setOrderno(code);
        payUtils.setAddrid("1565671633843224577");
        payUtils.setPaysort(paysort);
        //微信的工具类使用的是common里的
        com.aaa.util.PayUtils payUtils1 = new com.aaa.util.PayUtils();
        payUtils1.setTotalmoney(oPayLog.getTotalFee());
        payUtils1.setOrderno(code);
        payUtils1.setAddrid("1565671633843224577");
        payUtils1.setPaysort(paysort);
        if (paysort==1){
            Result payInfo = payService.getPayInfo(payUtils);
            return payInfo;
        }
        if (paysort==0){
            Result result = wxFeign.buyNow(payUtils1);
            return result;
        }
        return null;
    }

    @Override
    public Result paystateus(String code) throws AlipayApiException {
        Result paystatus = payService.paystatus(code);
        return paystatus;
    }

    @Override
    public Result status(String code) {
        Result result = wxFeign.payStatus(code);
        return result;
    }

    @Override
    public List<OOrder> findBycode(String code) {
        QueryWrapper<OOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("code",code);
        List<OOrder> oOrders = mapper.selectList(wrapper);
        return oOrders;
    }

    @Override
    public int updateSumNum(String residue, Integer id) {
        int i = oStockMapper.updateSumNum(residue, id);
        return i;
    }


    @Override
    public Result pageList(List<GoodsVo1> oOrders1) {
        String token = WebUtils.getRequest().getHeader("token");
        Map<String, Object> tokenChaim = JwtUtil.getTokenChaim(token);
        QueryWrapper<UUserInfo> uUserInfoQueryWrapper = new QueryWrapper<>();
        uUserInfoQueryWrapper.eq("telephone", tokenChaim.get("username"));
        UUserInfo uUserInfo = uUserInfoMapper.selectOne(uUserInfoQueryWrapper);
        int hashCode = java.util.UUID.randomUUID().toString().hashCode();
        if (hashCode < 0) {
            hashCode = -hashCode;
        }
        // 0 代表前面补充0
        // 10 代表长度为10
        // d 代表参数为正数型
        String format = String.format("%010d", hashCode).substring(0, 10);
        Result result = rabbitmqFeigen.makeChargeOrder(format);
        OOrder order;
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String times = sdf.format(date);
        int i = 1;
        OPayLog oPayLog = new OPayLog();
        oPayLog.setOrderNo(format);
        oPayLog.setPayType(1);
        oPayLog.setPaysort(1);
        oPayLog.setGmtCreated(date);
        oPayLog.setGmtModified(date);

        int sum = 0;
        for (GoodsVo1 order1 : oOrders1) {
            i++;
            order = new OOrder();
            order.setState(1);
            order.setGoodsid(String.valueOf(order1.getId()));
            order.setUid(uUserInfo.getId());
            order.setOrderdate(date);
            order.setAddrid(order1.getAddrid());
            order.setPaysort(1);
            order.setCommentstatus(0);
            order.setCode(format);
            BigDecimal price = order1.getPrice();
            order.setPrice(price);
            order.setSend(0);
            order.setBid(String.valueOf(order1.getId()));
            order.setNum(order1.getTotalNum());
            Integer bigInteger = Integer.valueOf(String.valueOf(order1.getPrice().toBigInteger()));
            Integer totalNum = order1.getTotalNum();
            sum = +totalNum;
            order.setTotalmoney((bigInteger * totalNum));
            oStockMapper.updateNum(order1.getTotalNum(), order1.getId());
            ocartDao.updatOne(order1.getId());
            mapper.insert(order);
            oPayLog.setTotalFee(BigDecimal.valueOf((bigInteger * totalNum)));
        }
        oPayLogMapper.insert(oPayLog);
        return new Result(2000, "success", format);
    }

    @Override
    public Result findByRepertory(List<GoodsVo1> oOrders1) {
        for (GoodsVo1 goodsVo1 : oOrders1) {
            QueryWrapper<OStock> wrapper = new QueryWrapper<>();
            wrapper.eq("goods_id", goodsVo1.getId());
            OStock oStock = oStockMapper.selectOne(wrapper);
            if (Integer.parseInt(oStock.getResidue()) - goodsVo1.getTotalNum() > 0) {
                return new Result(2000, "商品充足");
            } else {
                return new Result(5000, "货物不足");
            }

        }

        return null;
    }


}




